package com.community.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.community.annotation.SysLog;
import com.community.base.BaseService;
import com.community.common.Const;
import com.community.common.ServerResponse;
import com.community.pojo.AnswerComment;
import com.community.service.IAnswerCommentService;
import com.community.service.IJedisClientService;
import com.community.util.*;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 回答评论服务层
 */
@Service("iAnswerCommentService")
public class AnswerCommentServiceImpl extends BaseService implements IAnswerCommentService {

    @Autowired
    private IJedisClientService iJedisClientService;

    /**
     * 新增评论
     * @param paramMap
     * @return
     */
    @SysLog("新增评论")
    public ServerResponse<String> add(Map paramMap, HttpServletRequest request){
        String userName = StringUtil.valueOfString(paramMap.get("userName"));
        if(!LoginUtil.isLogin(request,userName)){
            return ServerResponse.createByErrorMessage(Const.Msg.PARAMTERERROR);
        }
        AnswerComment answerComment = new AnswerComment();
        answerComment.setAid(NumberUtil.safeToNumber(paramMap.get("aid")));//评论回答ID
        answerComment.setPid(NumberUtil.safeToNumber(paramMap.get("pid")));//该评论所在的父级id，没有则为0
        answerComment.setReplyid(NumberUtil.safeToNumber(paramMap.get("replyid")));//该评论回复的评论id，没有则为0
        answerComment.setContent(StringUtil.valueOfString(paramMap.get("content")));//评论内容
        answerComment.setCtype(NumberUtil.safeToNumber(paramMap.get("ctype")));//评论类型（1:回答,2:评论）
        answerComment.setTargetUser(StringUtil.valueOfString(paramMap.get("targetUser")));//被评论用户
        answerComment.setTimes(new Date());//时间
        answerComment.setIp(ToolUtil.getClientIp(request));//IP地址
        answerComment.setShow(NumberUtil.safeToNumber(paramMap.get("show")));//是否展示
        answerComment.setUsername(userName);//用户名
        if(answerCommentMapper.insert(answerComment) > 0){
            //更新回答评论数
            answerMapper.plusAnswerCommentNums(answerComment.getAid());
            return ServerResponse.createBySuccessMessage(Const.Msg.SAVESUCCESS);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SAVEERROR);
    }


    /**
     * 查询回答评论
     * @param pageNum
     * @param aid 回答ID
     * @return
     */
    @SysLog("查询回答评论")
    public ServerResponse<PageInfo> selectByAcid(int pageNum,int aid){
        //获取redis缓存
        String redisStr = iJedisClientService.get("aid:"+aid);
        if(StringUtil.isNotEmpty(redisStr)){//翻页情况下有缓存直接返回
            List<Map> cacheList =(List<Map>) JSONObject.parse(redisStr);
            ListSub<Map> listSub = new ListSub<Map>(pageNum, Const.MAXSIZE, cacheList);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(listSub.getTotal());
            pageInfo.setPages(listSub.getPages());
            pageInfo.setPageSize(listSub.getPageSize());
            pageInfo.setList(listSub.getList());
            return ServerResponse.createBySuccess(pageInfo);
        }
        //查询出所有该回答评论
        Map answerCommentMap = new HashMap<>();
        answerCommentMap.put("aid",aid);
        answerCommentMap.put("type",Const.CommentType.ONE);//只查回答评论
        //回答评论
        List<Map> answerCommentList = answerCommentMapper.selectByParamMap(answerCommentMap);
        if(null != answerCommentList && 0 < answerCommentList.size()){
            //根据点赞数排序
            Collections.sort(answerCommentList, new Comparator<Map>() {
                @Override
                public int compare(Map o1, Map o2) {
                    int o1Nums = NumberUtil.safeToNumber(o1.get("like_nums"));
                    int o2Nums = NumberUtil.safeToNumber(o2.get("like_nums"));
                    if(o1Nums > o2Nums){
                        return -1;
                    }
                    if(o1Nums == o2Nums){
                        return 0;
                    }
                    return 1;
                }
            });
            answerCommentMap.put("type",Const.CommentType.TWO);//只查评论对话
            //查询评论对话
            for (int i = 0; i < answerCommentList.size() ; i++) {
                Map commentMap = answerCommentList.get(i);
                int commentNums = NumberUtil.safeToNumber(commentMap.get("comment_nums"));
                if(commentNums > 0){
                    //有评论
                    answerCommentMap.put("replyid",NumberUtil.safeToNumber(commentMap.get("id")));
                    answerCommentMap.put("pid",NumberUtil.safeToNumber(commentMap.get("id")));
                    List<Map> mapList = answerCommentMapper.selectByParamMap(answerCommentMap);
                    if(null != mapList && 0 < mapList.size()){
                        //根据ID排序
                        Collections.sort(mapList, new Comparator<Map>() {
                            @Override
                            public int compare(Map o1, Map o2) {
                                int oId = NumberUtil.safeToNumber(o1.get("id"));
                                int o2Id = NumberUtil.safeToNumber(o2.get("id"));
                                if(oId > o2Id){
                                    return -1;
                                }
                                if(oId == o2Id){
                                    return 0;
                                }
                                return 1;
                            }
                        });
                        answerCommentList.get(i).put("dialogueList",mapList);
                    }
                }
            }
            //保存缓存
            iJedisClientService.set("aid:"+aid,JSONObject.toJSONString(answerCommentList));
            iJedisClientService.expire("aid:"+aid,Const.cacheTime);//缓存时间
            //分页
            ListSub<Map> listSub = new ListSub<Map>(pageNum, Const.MAXSIZE, answerCommentList);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(listSub.getTotal());
            pageInfo.setPages(listSub.getPages());
            pageInfo.setPageSize(listSub.getPageSize());
            pageInfo.setList(listSub.getList());
            return ServerResponse.createBySuccess(pageInfo);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SELECTERROR);
    }

}
